package edu.umn.contactviewer;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import edu.umn.contactviewer.datastore.ContactListDataService;
import edu.umn.contactviewer.datastore.ContactListDataService.RequestResult;
import edu.umn.contactviewer.datastore.DeleteContactRequestResponseListener;
import edu.umn.contactviewer.datastore.impl.ContactListDataServiceRESTWebServiceImpl;

/**
 * Displays a list of contacts.
 * 
 */
public class DeleteActivity extends ListActivity {

	private final ContactListDataService contactListDataStore;
	private final ArrayList<DeletionContactWrapper> contactListData;
	private ArrayAdapter<DeletionContactWrapper> contactListAdapter;
	private ContactsToolbar contactsToolbar = null;
	private int contactDeletionCount = 0;

	// Constructor
	public DeleteActivity() {
		contactListDataStore = new ContactListDataServiceRESTWebServiceImpl(this);
		contactListData = new ArrayList<DeletionContactWrapper>();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		contactsToolbar = new ContactsToolbar();

		// initialize the list view
		contactListAdapter = new ContactAdapter(this, R.layout.list_item,
				contactListData);

		// retrieve initial set of Contact list data
		updateContactListData();

		updateDeleteButtonStatus();
		
		setListAdapter(contactListAdapter);
		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
	}

	private void updateContactListData() {
		// clear the current data
		contactListData.clear();

		// retrieve fresh data from the datastore
		for (Contact contact : contactListDataStore.getContactList()) {
			contactListData.add(new DeletionContactWrapper(contact));
		}

		// notify the view to refresh itself
		contactListAdapter.notifyDataSetChanged();
	}

	private void updateDeleteButtonStatus() {
		int visibility = (0 < contactDeletionCount ? View.VISIBLE : View.INVISIBLE);
		contactsToolbar.getDeleteButton().setVisibility(visibility);
	}

	/*
	 * We need to provide a custom adapter in order to use a custom list item
	 * view.
	 */
	public class ContactAdapter extends ArrayAdapter<DeletionContactWrapper> {

		public ContactAdapter(Context context, int textViewResourceId,
				List<DeletionContactWrapper> objects) {
			super(context, textViewResourceId, objects);
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View item = inflater.inflate(R.layout.delete_list_item, parent,
					false);

			Contact contact = getItem(position).getContact();
			((TextView) item.findViewById(R.id.item_name)).setText(contact
					.getName());
			((TextView) item.findViewById(R.id.item_title)).setText(contact
					.getTitle());
			((TextView) item.findViewById(R.id.item_phone)).setText(contact
					.getPhone());

			// attach listener to checkbox to update contact deletion status
			((CheckBox) item.findViewById(R.id.item_delete_checkbox))
					.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							CheckBox checkBox = (CheckBox) v;
							DeletionContactWrapper deletionContactWrapper = (DeletionContactWrapper) contactListAdapter
									.getItem(position);
							deletionContactWrapper.markForDeletion(checkBox
									.isChecked());
							if (checkBox.isChecked()) {
								++contactDeletionCount;
							} else {
								--contactDeletionCount;
							}
							
							updateDeleteButtonStatus();
						}
					});

			return item;
		}
	}

	private class ContactsToolbar extends ToolbarConfig {
		public ContactsToolbar() {
			super(DeleteActivity.this, getString(R.string.delete_contacts));
			// initialize the create button and add action listener
			Button rightButton = getToolbarRightButton();
			rightButton.setText(getString(R.string.delete));
			rightButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					for (DeletionContactWrapper deletionContactWrapper : contactListData) {
						if (deletionContactWrapper.isMarkedForDeletion()) {
							
							// Make asynchronous delete request
							contactListDataStore.deleteContact(
								deletionContactWrapper.getContact(), 
								new DeleteContactRequestResponseListener() {
									public void onDeleteContactResponse(RequestResult result, Contact contactToDelete) {
										if (result == RequestResult.SUCCESS) {
											Toast.makeText(
												getApplicationContext(),
												getString(R.string.deletion_success_message),
												5).show();
											setResult(RESULT_OK);
											finish();
										}
										else {
											Log.e(DeleteActivity.class.getSimpleName(),
												  "Error deleting contact: " + contactToDelete.getName());
										}
									}
								});
							
						} // end if contact marked for deletion
					} // end loop on contacts
				} // end Delete button onClick
			}); // end Delete button setOnClickListener
			rightButton.setVisibility(View.VISIBLE);
		}

		public Button getDeleteButton() {
			return getToolbarRightButton();
		}
	}

	private class DeletionContactWrapper {
		private Boolean markedForDeletion;
		private final Contact contact;

		public DeletionContactWrapper(Contact contact) {
			this.contact = contact;
			this.markedForDeletion = Boolean.FALSE;
		}

		public Contact getContact() {
			return contact;
		}

		public void markForDeletion(Boolean markedForDeletion) {
			this.markedForDeletion = markedForDeletion;
		}

		public Boolean isMarkedForDeletion() {
			return markedForDeletion;
		}
	}
}
